import { envConfigs } from "../config/index";
import { ALL_END, BOTH_GOAL, DA_SI_MA, GAMEING, initialState, LEFT_PREFIX_RIGHT } from "../const/index";

export const generateRandomString = (length = 6) => {
  const characters = "abcdefghijklmnopqrstuvwxyz";
  let result = "";
  const charactersLength = characters.length;
  for (let i = 0; i < length; i++) {
    const randomIndex = Math.floor(Math.random() * charactersLength);
    result += characters.charAt(randomIndex);
  }
  return result;
}

// 根据文本，寻找dom元素
export const findElementByTextDFS = (element: Element, searchText: string): HTMLDivElement | HTMLElement | Element | null => {
  if (!element) return null;

  // 检查当前元素的 innerText
  if (element.textContent === searchText) {
    return element;
  }

  // 递归遍历子元素
  const { children } = element;
  for (let i = 0; i < children.length; i++) {
    const result = findElementByTextDFS(children[i], searchText);
    if (result) {
      return result;
    }
  }

  // 如果没有找到符合条件的元素，返回 null
  return null;
}

// 找到主播并且点击他
export const findZhuboCardItemAndClick = (name: string) => {
  const cList = document.getElementsByClassName("card_list")?.[0];
  const zhuboElement = findElementByTextDFS(cList, name);
  if (zhuboElement) {
    zhuboElement?.parentElement?.parentElement?.parentElement?.click();
    return true;
  }
  console.log("[zjymock:]", "没找到主播", name);
  return false;
}


export const getCurrentZhubo = (name: string) => {
  const cList = document.getElementsByClassName("card_list")?.[0];
  const zhuboElement = findElementByTextDFS(cList, name);
  if (zhuboElement) {
    return true;
  }
  console.log("[zjymock:]", "没找到主播", name);
  return false;
}

// 通过阿里云返回的结构判断是否在一行，同一行的文本放在一起
export const combineItemsBasedOnXDifference = (items: { pos: { x: number, y: number }[], word: string }[]) => {
  if (!items) {
    return [];
  }
  const combinedItems = [];
  const usedIndexes = new Set(); // 用来记录已经参与组合的项索引

  for (let i = 0; i < items.length; i++) {
    if (usedIndexes.has(i)) continue; // 如果当前项已经被使用过，则跳过

    let foundMatch = false;
    for (let j = i + 1; j < items.length; j++) {
      if (usedIndexes.has(j)) continue; // 如果对比项已经被使用过，则跳过

      let allPointsMatch = true;
      for (let k = 0; k < items[i].pos.length; k++) {
        if (Math.abs(items[i].pos[k].y - items[j].pos[k].y) > 3) {
          allPointsMatch = false;
          break;
        }
      }

      if (allPointsMatch) {
        combinedItems.push(items[i].word + LEFT_PREFIX_RIGHT + items[j].word);
        usedIndexes.add(i);
        usedIndexes.add(j); // 标记这两项已被使用
        foundMatch = true;
        break; // 找到匹配后停止查找其他的匹配项
      }
    }

    // 如果没有找到匹配项，则自己push一条数据
    if (!foundMatch && !usedIndexes.has(i)) {
      combinedItems.push(items[i].word);
    }
  }
  return combinedItems
}

export const combinedItemsToTextArr = (combinedItems: string[]) => {
  const result = []
  for (let i = 0; i < combinedItems.length; i++) {
    const w = combinedItems[i];
    if (w?.includes('收') || w?.includes('重注')) {
      continue;
    }
    if (w?.includes('月')) {
      continue
    }
    if (w?.includes('捐')) {
      continue
    }
    if (w?.includes('等水')) {
      continue
    }

    if (w?.includes('均注') && envConfigs.iszhongchui) {
      break;
    }
    result.push(w);
  }
  const textArr = result.map(word => {
    let str = word.split(LEFT_PREFIX_RIGHT)?.[0] || ''

    if (str === '客0') {
      str = '客-0'
    }
    if (str === '主0') {
      str = '主-0'
    }
    if (str?.includes('双方进球') && str?.includes('/')) {
      str = '双方进球'
    }

    // 处理 74追主-1.5角 10客队-1 这种情况
    const regex = /^(\d{2,3})(追|时|)(.*)$/;
    const match = str.match(regex);
    if (match) {
      str = `1:${match?.[1]}${match?.[3]}`
    }

    return `【${str}】${initialState.dsmpay}张`
  })
  console.log('zjymock', { textArr });
  return textArr;
}

export const getHHmmss = () => {
  const now = new Date();
  const hours = now.getHours();
  const minutes = now.getMinutes();
  const seconds = now.getSeconds();
  return `当前时间是 ${hours}:${minutes}:${seconds}`;
}

export const getGameStatus = () => {
  const gameTimeDom = document.getElementsByClassName(
    "vh_center_center pdlr-10"
  )?.[0] as HTMLElement;
  if (
    gameTimeDom.innerText.includes("已结束") ||
    gameTimeDom.innerText.includes("常规时间结束") ||
    gameTimeDom.innerText.includes("全场结束")
  ) {
    return ALL_END;
  }
  return GAMEING;
}

export const sleep = (ms: number) => {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

export const containsAnyCharacter = (str: string, charArray: string[]) => {
  for (let char of str) {
    if (charArray.includes(char)) {
      return true;
    }
  }
  return false;
}

export const str1HasStr2 = (str1: string, str2: string) => {
  for (let i = 0; i < str2?.length; i++) {
    let charToFind = str2?.[i];
    let foundIndex = -1;
    for (let j = 0; j < str1?.length; j++) {
      if (str1?.[j] === charToFind) {
        foundIndex = j;
        break;
      }
    }
    if (foundIndex === -1) {
      return false;
    }
  }
  return true;
}